import re
from urllib.parse import quote_plus, unquote_plus
import json

def escape(value):
    return value.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;").replace("\"", "&quot;")

def json_encode(value):
    """JSON-encodes the given Python object."""
    # JSON permits but does not require forward slashes to be escaped.
    # This is useful when json data is emitted in a <script> tag
    # in HTML, as it prevents </script> tags from prematurely terminating
    # the javscript.  Some json libraries do this escaping by default,
    # although python's standard library does not, so we do it here.
    # http://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped
    return json.dumps(value).replace("</", "<\\/")


def json_decode(value):
    """Returns Python objects for the given JSON string."""
    return json.loads(value)

def add_class(cls1, cls2):
    if not cls1:
        return cls2
    else:
        return cls1 + ' ' + cls2 if cls2 else cls1


def highlight(text, phrases, highlighter=r'<strong class="highlight">\1</strong>'):
    text = xhtml_escape(text)
    if not phrases: 
        return text
    if isinstance(phrases, (tuple, list)):
        pattern = '|'.join([re.escape(phrase) for phrase in phrases])
        return re.sub(r'(' + pattern + ')', highlighter, text)
    else:
        return phrases.sub(highlighter, text)
    
_cache = {}

def cache(key, func, view_specific=True):
    if view_specific:
        from bodhi.web import View
        match_data = View.current.match_data
        key = '{}.{}:{}'.format(match_data['module'], match_data['view'], key)
    try:
        return _cache[key]
    except KeyError:
        _cache[key] = func()
        return _cache[key]
